#include "event_loop.h"
#include "logger.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <cassert>

using namespace net;
using namespace std;
using namespace chrono;

// 测试1：EventLoop单线程任务执行
void test_single_loop() 
{
    cout << "Testing signle eventLoop..." << endl;
    const string logFile = "test_single_loop.log";
    Logger::instance().init(logFile, 1024*1024, 1);
    Logger::instance().setLevel(LogLevel::INFO);
    LOG_INFO("=== Testing single EventLoop ===");
    EventLoop loop;

    // 提交任务到EventLoop线程
    loop.queueInLoop([]() {
        LOG_INFO("Task 1 executed in thread: %d", this_thread::get_id());
    });

    // 启动线程执行EventLoop
    thread t([&loop]() {
        loop.start();
    });

    // 等待任务执行
    this_thread::sleep_for(std::chrono::milliseconds(100));
    loop.queueInLoop([&loop]() {
        LOG_INFO("Task 2: Stop loop");
        // 实际项目中需通过标志位退出循环，此处简化
        loop.quit();
    });

    t.join();
    LOG_INFO("Single loop test passed\n");
}

// 测试2：LoopThreadPool轮询分配
void test_thread_pool() 
{
    cout << "Testing threadPool..." << endl;
    const string logFile = "test_thread_pool.log";
    Logger::instance().init(logFile, 1024*1024, 1);
    Logger::instance().setLevel(LogLevel::INFO);
    LOG_INFO("=== Testing LoopThreadPool ===");
    EventLoop base_loop;
    LoopThreadPool pool(&base_loop);
    pool.setThreadCount(3); // 3个子线程
    pool.create();

    // 提交5个任务，验证轮询分配
    for (int i = 0; i < 5; ++i) {
        EventLoop* loop = pool.nextLoop();
        loop->queueInLoop([i, loop]() {
            LOG_INFO("Task %d executed in loop thread: %d", 
                     i, loop->threadId()); // 需在EventLoop中添加ThreadId()接口
        });
    }
    // 等待任务执行
    this_thread::sleep_for(std::chrono::milliseconds(100));

    LOG_INFO("ThreadPool test passed\n");

    LOG_INFO("Stopping all event loops...");

    // 等待所有线程退出
    this_thread::sleep_for(std::chrono::milliseconds(200));
}

// 测试3：定时器功能
void test_timer() {
    cout << "Testing timer..." << endl;
    const string logFile = "test_timer.log";
    Logger::instance().init(logFile, 1024*1024, 1);
    Logger::instance().setLevel(LogLevel::INFO);
    LOG_INFO("=== Testing TimerWheel ===");
    EventLoop loop;

    // 添加1s后执行的定时器
    uint64_t timer_id = 1;
    loop.timerAdd(timer_id, 1, []() {
        LOG_INFO("Timer 1s triggered");
    });

    // 启动EventLoop
    thread t([&loop]() {
        loop.start();
    });

    // 验证定时器存在
    assert(loop.hasTimer(timer_id) == true);

    // 等待定时器执行
    this_thread::sleep_for(std::chrono::milliseconds(2000));
    assert(loop.hasTimer(timer_id) == false); // 执行后自动移除

    loop.queueInLoop([&loop]() {
        LOG_INFO("Stop timer test");
        loop.quit();
    });

    t.join();
    LOG_INFO("Timer test passed\n");
}

int main() 
{
    test_single_loop();
    test_thread_pool();
    test_timer();
    return 0;
}